/* eslint-disable react-hooks/exhaustive-deps */
import React, { useContext, useEffect } from 'react'
import { Row, Col, Button, Empty } from 'antd';
import ReactEcharts from 'echarts-for-react'
import ProForm, { ProFormSelect } from '@ant-design/pro-form';
import styles from './index.less';
import { getClassList, getCourseListOption, getVideoUser } from '@/services/student';
import { CourseContext } from '../../..';
import moment from 'moment';
import { useState } from 'react';
import { echartOption } from '@/utils/echartsUtils';
interface Params {
  type: number
}
export default function StudyInfo(props: Params) {
  const ctx = useContext(CourseContext);
  const { type } = props;
  const [option, setOption] = useState();
  const [data1, setData1] = useState<any[]>([]);
  const [data2, setData2] = useState<any[]>([]);
  const [data22, setOptionList] = useState<any>();
  const [result, setResult] = useState<any>()
  useEffect(() => {
    (async () => {
      const params = {
        courseId: ctx.courseId,
        uid: ctx.uid,
        itemId: option,
      }
      let res1;
      let res2;
      if (type == 1) {
        if (option) {
          res1 = await getClassList({ ...params, type: 2 })
          setData1(res1?.result?.records)
          res2 = await getClassList({ ...params, typeList: [4, 5, 6] })
          setData2(res2?.result?.records)

        }
      } else {
        if (option) {
          res1 = await getVideoUser({ ...params });
          setData1(res1?.result)
          setData2(res1?.result)
        }
      }
    })()
  }, [ctx, option])
  useEffect(() => {
    (async () => {
      const params = {
        uid: ctx.uid, courseId: ctx.courseId, pageSize: -1, isUnlock: 1
      }
      if (type == 1) {
        params[`stepTypeList`] = [0, 6]
      }
      if (type == 2) {
        params['stepType'] = 1
      }
      const res = (await getCourseListOption(params))?.result?.records;
      setResult(res);
      const list = res?.map((item: any) => {
        return { label: `${item.name}(${moment(item.startTime).format('YYYY.MM.DD')})`, value: item.id }
      })
      if (option == null) {
        setOption(list?.[list?.length - 1]?.value);
      }
      setOptionList(list)
    })()
  }, [ctx])

  const getTotal = (data: any[], getItem: (item: any) => any) => {
    return data?.map((item) => {
      return getItem(item);
    })?.reduce((total, value) => {
      return total + value
    }, 0) ?? 0;
  }
  let data1JoinCount, data2JoinCount, data1RightCount, data1WrongCount, data1TotalCount,
    data1UnanswerCount, data2RightCount, data2WrongCount, data2TotalCount, data2UnanswerCount

  if (option) {

    data1JoinCount = getTotal(data1, (item) => item.joinCount);
    data2JoinCount = getTotal(data2, (item) => item.joinCount);

    data1RightCount = getTotal(data1, (item) => item.rightCount || item.markQuestionRightCount);
    data1WrongCount = getTotal(data1, (item) => item.joinCount - item.rightCount || item.markQuestionWrongCount);
    data1TotalCount = getTotal(data1, (item) => item.allCount || item.markQuestionCount);
    data1UnanswerCount = (data1TotalCount - data1JoinCount) || (data1TotalCount - data1RightCount - data1WrongCount);
    data2RightCount = getTotal(data2, (item) => item.rightCount || item.interactiveQuestionRightCount);
    data2WrongCount = getTotal(data2, (item) => item.joinCount - item.rightCount || item.interactiveQuestionWrongCount);
    data2TotalCount = getTotal(data2, (item) => item.allCount || item.interactiveQuestionCount);
    data2UnanswerCount = (data2TotalCount - data2JoinCount) || (data2TotalCount - data2RightCount - data2WrongCount);
  }

  const dataList = [
    { value: data1RightCount, name: `正确`, color: "green" },
    { value: data1WrongCount, name: `不正确`, color: "#FF66CC" },
    { value: data1UnanswerCount, name: `未作答`, color: "grey" },
  ]
  const dataList1 = [
    { value: data2RightCount, name: `正确`, color: "green" },
    { value: data2WrongCount, name: `不正确`, color: "#FF66CC" },
    { value: data2UnanswerCount, name: `未作答`, color: "grey" },
  ]

  const goStudy = () => {
    console.log(option);

    console.log(result?.find((item: any) => item.id == option).courseStepId);

    if (type == 1) {

      const w = window.open('_black');
      w!.location.href = `/web/gospirit_webview/study_report?token=${localStorage.getItem('token')}&uid=${ctx.uid}&stepId=${result?.find((item: any) => item.id == option).courseStepId}`
    } else {
      const w = window.open('_black');
      w!.location.href = `/web/gospirit_webview/study_report?token=${localStorage.getItem('token')}&uid=${ctx.uid}&stepId=${result?.find((item: any) => item.id == option).courseStepId}`
    }
  }

  return (
    <div>
      {
        data22 && data22.length !== 0 ?
          <div style={{ textAlign: 'left' }}>
            <Row className={styles.right_pro_form_style}>
              <Col span={18}>
                <ProForm
                  style={{ width: "70%", float: 'right' }}
                  layout="horizontal"
                  colon={true}
                  labelAlign='right'
                >
                  <ProFormSelect
                    colProps={{ xl: 8, md: 12 }}
                    label="条目"
                    name="required"
                    fieldProps={{
                      onChange: (val) => { setOption(val) },
                      value: option,
                      allowClear: false,
                      autoFocus: false
                    }}
                    options={data22}

                  />
                </ProForm>
              </Col>
              <Col span={6} style={{ textAlign: 'center' }}>
                <Button type="primary" className={styles.btn} onClick={goStudy}>查看学习报告</Button>
              </Col>
            </Row>

          </div> : null
      }
      {
        !option ? null :
          <Row style={{ marginTop: '20px' }}>
            <div style={{ flex: 1, marginBottom: '15px', position: 'relative' }}>
              <div style={{ fontSize: '18px', fontWeight: 'bold', left: "50%", transform: 'translateX(-50%)', position: 'absolute' }}>标记题正确率({data1TotalCount || 0})</div>

              {
                type == 1 ? (!data1JoinCount || data1JoinCount == 0) ? <Empty style={{ marginTop: '50px' }} description={'直播课开没有开始哦'} image={Empty.PRESENTED_IMAGE_SIMPLE} /> :
                  <ReactEcharts notMerge option={echartOption(dataList)} /> : null

              }
              {
                type == 2 ? ((!data1RightCount) && (!data1WrongCount) && (!data1UnanswerCount || data1UnanswerCount == 0)) ? <Empty style={{ marginTop: '50px' }} description={'还没有已解锁的互动视频课'} image={Empty.PRESENTED_IMAGE_SIMPLE} /> :
                  <ReactEcharts notMerge option={echartOption(dataList)} /> : null

              }
            </div>
            <div style={{ flex: 1, marginBottom: '15px', position: 'relative' }}>
              <div style={{ fontSize: '18px', fontWeight: 'bold', left: "50%", transform: 'translateX(-50%)', position: 'absolute' }}>互动课件正确率({data2TotalCount || 0})</div>

              {
                type == 1 ? (!data2JoinCount || data2JoinCount == 0) ?
                  <Empty description={'直播课开没有开始哦'} style={{ marginTop: '50px' }} image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  :
                  <ReactEcharts notMerge option={echartOption(dataList1)} /> : null
              }
              {
                type == 2 ? (!data2RightCount &&
                  !data2WrongCount && (!data2UnanswerCount || data2UnanswerCount == 0)) ?
                  <Empty description={'还没有已解锁的互动视频课'} style={{ marginTop: '50px' }} image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  :
                  <ReactEcharts notMerge option={echartOption(dataList1)} /> : null
              }
            </div>
          </Row>
      }
    </div>
  )
}
